package com.yehebl.orm.data.mysql;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Set;

import com.yehebl.orm.util.LogUtil;


/**
 * mysql 实体和表效验
 */
public class MySqlValidateField {
	public static Set<String> getColumns(Connection connection, String tableName) {
		try {
			Set<String> set = new HashSet<>();
			DatabaseMetaData dbmd = connection.getMetaData();
			ResultSet rs = dbmd.getColumns(null, "%", tableName, "%");
			while (rs.next()) {
				set.add(rs.getString("COLUMN_NAME"));
			}
			rs.close();
			connection.close();
			return set;
		} catch (Exception e) {
			LogUtil.printWarn("获取表["+tableName+"]列名信息出错,"+e.getMessage());
			throw new RuntimeException("获取表["+tableName+"]列名信息出错,"+e.getMessage());
		}
	}

	public static Set<String> getKeys(Connection connection, String tableName) {
		try {
			Set<String> set = new HashSet<>();
			DatabaseMetaData dbmd = connection.getMetaData();
			ResultSet rs = dbmd.getPrimaryKeys(null, "%", tableName);
			while (rs.next()) {
				set.add(rs.getString("COLUMN_NAME"));
			}
			rs.close();
			connection.close();
			return set;
		} catch (Exception e) {
			LogUtil.printWarn("获取表["+tableName+"]主键信息出错,"+e.getMessage());
			throw new RuntimeException("获取表["+tableName+"]主键信息出错,"+e.getMessage());
		}
	}
}
